package com.ruoyi.system.service.impl;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.system.domain.SysBanner;
import com.ruoyi.system.mapper.SysBannerMapper;
import com.ruoyi.system.service.ISysBannerService;

@Service
public class SysBannerServiceImpl implements ISysBannerService{
	
	
	private static final Logger log = LoggerFactory.getLogger(SysBannerServiceImpl.class);

	
	@Autowired
	SysBannerMapper sysBannerMapper;

	@Override
	public List<SysBanner> selectBannerAll(SysBanner banner) {
		// TODO Auto-generated method stub
		List<SysBanner> list = sysBannerMapper.selectList(new QueryWrapper<SysBanner>(banner).orderByAsc("id"));
		return list;
	}

	@Override
	public void insertBanner(SysBanner banner) {
		// TODO Auto-generated method stub
		sysBannerMapper.insert(banner);
	}

	@Override
	@Transactional(rollbackFor = RuntimeException.class)
	public void removeBanner(String ids) {
		if(ids.contains(",")) {
			String [] idArray = ids.split(",");
			for(String id:idArray) {
				removeBanner(id);
			}
		}else {
			removeFile(ids);
		}
		
	} 
	
	private void removeFile(String id) {
		SysBanner banner = sysBannerMapper.selectById(id);
		File file = new File(banner.getBannerUrl());
		if(file.exists()) {
			file.delete();
			sysBannerMapper.deleteById(id);
		}else {
			log.error("文件不存在，文件路径：{}",banner.getBannerUrl());
			try {
				throw new Exception("文件不存在！");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public SysBanner selectOneById(Integer id) {
		// TODO Auto-generated method stub
		return sysBannerMapper.selectById(id);
	}

	@Override
	public void updateBannerById(SysBanner banner) {
		// TODO Auto-generated method stub
		 sysBannerMapper.updateById(banner);
	}

	@Override
	public void removeFileByurl(String url) {
		File file = new File(url);
		if(file.exists()) {
			file.delete();
		}else {
			log.error("文件不存在，文件路径：{}",url);
			try {
				throw new Exception("文件不存在！");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}
